package itsm.isperp.module.controller.api.mobile;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.utils.JsonBuilder;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.controller.task.TskTaskController;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.entity.task.TskTask;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.task.TskTaskService;
import itsm.isperp.workflow.service.BpmProcessRunService;
import itsm.isperp.workflow.utils.BpmConst;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 
 * 手机端任务接口控制器
 * 
 * @author zhouhg
 * @date 2014-3-25
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("api/mobile/task")
public class MobileTaskController {

	public static final Logger logger = LoggerFactory
			.getLogger(MobileTaskController.class);

	/**
	 * 获取待办事件列表
	 * 
	 * @param username
	 * @param password
	 * @param req
	 * @return
	 */
	@RequestMapping("list")
	@ResponseBody
	public ResultMessage list(String username) {
		TskTaskService tskTaskService = ContextHolder
				.getSpringBean(TskTaskService.class);
		try {
			// to do
			JqGridRequest request = new JqGridRequest();
			request.setPageable(false);
			request.setSelectColumns("id", "name", "priority", "status",
					"creator_name", "plan_start_time", "plan_end_time");
			request.setSort("id", Direction.DESC);

			TskTaskController tskTaskController = ContextHolder
					.getSpringBean(TskTaskController.class);

			request.setSearchString(BpmConst.getQueryTaskSqlCondition(
					tskTaskController.getProceessKey(), "'" + username + "'"));

			List<Map<String, Object>> list = tskTaskService
					.findAllDetailByRequest(request).getContent();

			return ResultMessage.success(JsonBuilder.buildNormalBinder()
					.toJson(list));

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("获取待办任务列表失败，原因是：" + e.getMessage());
		}

	}

	/**
	 * 获取已办任务列表
	 * 
	 * @param username
	 *            用户名
	 * @param type
	 *            加载方式（1：加载更多，0加载历史）
	 * @param taskId
	 *            任务id（id具有排序功能）
	 * @param size
	 *            加载数量（默认20）
	 * @return
	 */
	@RequestMapping("listHandled")
	@ResponseBody
	public ResultMessage listHandled(String username, String type,
			String taskId, Integer size) {

		TskTaskService tskTaskService = ContextHolder
				.getSpringBean(TskTaskService.class);
		try {
			// to do
			JqGridRequest request = new JqGridRequest();
			request.setPageable(true);
			request.setRows(size);
			request.setSort("id", Direction.DESC);

			if (type.equalsIgnoreCase("1") && StringUtils.isNotEmpty(taskId)) // 加载更多
			{
				request.addFilterRule("id", JqGridFilterRuleOp.lt, taskId);
			}

			request.setSelectColumns("id", "name", "priority", "status",
					"creator_name", "plan_start_time", "plan_end_time");

			TskTaskController tskTaskController = ContextHolder
					.getSpringBean(TskTaskController.class);

			request.setSearchString(BpmConst.getQueryMyTaskAttendSqlCondition(
					tskTaskController.getProceessKey(), username));

			List<Map<String, Object>> list = tskTaskService
					.findAllDetailByRequest(request).getContent();

			return ResultMessage.success(JsonBuilder.buildNormalBinder()
					.toJson(list));

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("获取已办任务列表失败，原因是：" + e.getMessage());
		}

	}

	/**
	 * 获取任务明细信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("taskDetail")
	@ResponseBody
	public ResultMessage taskDetail(String id) {
		try {

			TskTaskService tskTaskService = ContextHolder
					.getSpringBean(TskTaskService.class);

			Map<String, Object> task = tskTaskService.findOneDetailById(id);

			return ResultMessage.success(JsonBuilder.buildNormalBinder()
					.toJson(task));

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("获取任务详情失败，原因是：" + e.getMessage());
		}

	}

	/**
	 * 任务处理接口
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("taskSolve")
	@ResponseBody
	public ResultMessage taskSolve(String id, String solver_name,
			Boolean finished, String handle_desc, Float act_times,
			String handle_type, String next_tran_id) {
		try {

			TskTaskService tskTaskService = ContextHolder
					.getSpringBean(TskTaskService.class);
			TskTask tskTask = tskTaskService.findOne(id);
			if (tskTask != null) {

				tskTask.setStatus("完成");
				tskTask.setFinished(finished);
				// tskTask.setActEndTime(new Timestamp(new Date().getTime()));
				tskTask.setHandleDesc(handle_desc);

				tskTask.setActTimes(act_times == null ? 0 : Float
						.valueOf(act_times));
				tskTask.setActPrincipalId(solver_name);

				AppUserService appUserService = ContextHolder
						.getSpringBean(AppUserService.class);

				AppUser appUser = appUserService.findByUsername(solver_name);

				tskTask.setActPrincipalName(appUser.getFullname());

				switch (handle_type) {
				case "1": // 保存
					tskTaskService.saveOrUpdate(tskTask);
					break;
				case "2": // 提交
					tskTaskService.saveOrUpdate(tskTask);
					BpmProcessRunService bpmProcessRunService = ContextHolder
							.getSpringBean(BpmProcessRunService.class);

					bpmProcessRunService.gotoNextSetp(solver_name,
							"incidentProcess", null, next_tran_id,
							tskTask.getProcessId(), id, null, null, 0, 0);
					break;

				default:
					break;
				}
				Map<String, String> ret = new HashMap<String, String>();
				ret.put("status", tskTask.getStatus());
				return ResultMessage.success(JsonBuilder.buildNormalBinder()
						.toJson(ret));
			} else {
				return ResultMessage.failure("操作失败，该事件已被删除");
			}

		} catch (Exception e) {

			logger.error(e.getMessage(), e);

			return ResultMessage.failure("操作失败，原因是：" + e.getMessage());
		}

	}
}
